<template>
  <div class="home-container">
    <div class="chat-layout">
      <!-- 左侧会话列表 -->
      <div class="session-sidebar">
        <div class="sidebar-header">
          <h3>聊天会话</h3>
          <el-button type="primary" @click="createNewSession" size="small">
            <el-icon><Plus /></el-icon>
            新建会话
          </el-button>
        </div>
        <div class="session-list">
          <div
              v-for="session in sessionList"
              :key="session.conversation_id"
              :class="['session-item', { active: currentSessionId === session.conversation_id }]"
              @click="selectSession(session)"
          >
            <div class="session-title">{{ session.title || '新会话' }}</div>
            <div class="session-time">{{ formatSessionTime(session.timestamp) }}</div>
            <div class="session-preview">{{ session.preview || '暂无消息' }}</div>
          </div>
        </div>
      </div>

      <!-- 右侧聊天区域 -->
      <div class="chat-container">
        <!-- 聊天消息区域 -->
        <div class="chat-messages" ref="messagesContainer">
          <div
              v-for="(message, index) in chatMessages"
              :key="index"
              :class="['message', message.role]"
          >
            <div class="message-avatar">
              <el-avatar
                  v-if="message.role === 'ai'"
                  :size="32"
                  src="https://cdn-icons-png.flaticon.com/512/4712/4712035.png"
              />
              <el-avatar
                  v-else
                  :size="32"
                  :src="userStore.avatar_url || 'https://cdn-icons-png.flaticon.com/512/3135/3135715.png'"
              />
            </div>
            <div class="message-content">
              <div class="message-header">
                <span class="sender-name">
                  {{ message.role === 'ai' ? 'AI助手' : userStore.username || '用户' }}
                </span>
                <span class="message-time">{{ message.time }}</span>
              </div>
              <div class="message-text">
                <span v-if="message.isStreaming && message.role === 'ai'" class="streaming-cursor"></span>
                {{ message.content }}
              </div>
            </div>
          </div>

          <!-- 加载状态 -->
          <div v-if="isLoading" class="loading-indicator">
            <el-icon class="is-loading"><Loading /></el-icon>
            <span>AI正在思考中...</span>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="input-area">
          <div class="input-container">
            <el-input
                v-model="userInput"
                type="textarea"
                :rows="3"
                placeholder="请输入您的问题..."
                :disabled="isLoading"
                @keydown.enter.exact.prevent="handleSendMessage"
                resize="none"
            />
            <el-button
                type="primary"
                :loading="isLoading"
                :disabled="!userInput.trim()"
                @click="handleSendMessage"
                class="send-button"
            >
              {{ isLoading ? '发送中...' : '发送' }}
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, watch } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import { Plus, Loading } from '@element-plus/icons-vue'
import { useloginUserStore } from '../store/loginUserInfo.js'
import axios from '../axiosInstance.js'

const userStore = useloginUserStore()
const messagesContainer = ref(null)
const isLoading = ref(false)
const userInput = ref('')
const requestStatus = ref('等待请求')

// 会话相关数据
const sessionList = ref([])
const currentSessionId = ref(null)
const currentSessionTitle = ref('')

// 聊天消息数据
const chatMessages = reactive([])

// 自动滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 格式化时间
const formatTime = (date = new Date()) => {
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

// 格式化会话时间
const formatSessionTime = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now - date

  if (diff < 24 * 60 * 60 * 1000) {
    // 今天内的消息
    return formatTime(date)
  } else if (diff < 7 * 24 * 60 * 60 * 1000) {
    // 一周内的消息
    const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    return days[date.getDay()]
  } else {
    // 更早的消息
    return `${date.getMonth() + 1}/${date.getDate()}`
  }
}

// 获取会话列表
const fetchSessions = async () => {
  if (!userStore.user_id) {
    ElMessage.warning('请先登录')
    return
  }

  try {
    const response = await axios.post(`http://localhost:19000/session/${userStore.user_id}`, {
      user_id: userStore.user_id
    })

    if (response.data.code === 200) {
      // 处理会话数据并按时间倒序排序（最新的在最上面）
      sessionList.value = response.data.data.map(sessionMessages => {
        const firstMessage = sessionMessages[0]
        const lastMessage = sessionMessages[sessionMessages.length - 1]

        return {
          conversation_id: firstMessage.conversation_id,
          title: sessionMessages.length > 0 ?
              (sessionMessages[0].content.slice(0, 20) + (sessionMessages[0].content.length > 20 ? '...' : '')) :
              '新会话',
          preview: lastMessage ? lastMessage.content.slice(0, 50) + (lastMessage.content.length > 50 ? '...' : '') : '',
          timestamp: lastMessage ? lastMessage.timestamp : new Date().toISOString(),
          messages: sessionMessages
        }
      }).sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp)) // 按时间倒序排序

      // 如果有会话，默认选择第一个（最新的）
      if (sessionList.value.length > 0 && !currentSessionId.value) {
        selectSession(sessionList.value[0])
      }
    } else {
      ElMessage.error('获取会话列表失败: ' + response.data.msg)
    }
  } catch (error) {
    console.error('获取会话列表失败:', error)
  }
}

// 选择会话
const selectSession = (session) => {
  // 如果点击的是当前已选中的会话，则不重复处理
  if (currentSessionId.value === session.conversation_id) {
    return
  }

  currentSessionId.value = session.conversation_id
  currentSessionTitle.value = session.title

  // 清空当前消息
  chatMessages.splice(0, chatMessages.length)

  // 加载会话消息
  if (session.messages && session.messages.length > 0) {
    session.messages.forEach(msg => {
      chatMessages.push({
        role: msg.type === 'USER' ? 'user' : 'ai',
        content: msg.content,
        time: formatTime(new Date(msg.timestamp)),
        isStreaming: false
      })
    })
  }

  scrollToBottom()
}

// 创建新会话
const createNewSession = () => {
  // 清空当前会话ID，表示这是一个新会话
  currentSessionId.value = null
  currentSessionTitle.value = '新会话'

  // 清空当前消息
  chatMessages.splice(0, chatMessages.length)

  // 添加欢迎消息
  chatMessages.push({
    role: 'ai',
    content: '您好！我是AI助手，很高兴为您服务。请问有什么可以帮助您的吗？',
    time: formatTime(),
    isStreaming: false
  })

  // 确保不会自动跳转到历史会话
  // 这里不需要选择任何历史会话，保持当前的新会话状态
}

// 创建会话并获取ID
const createSessionAndGetId = async (userMessage) => {
  try {
    const response = await axios.post('http://localhost:19000/session/set', {
      user_id: userStore.user_id,
      title: userMessage.slice(0, 20) + (userMessage.length > 20 ? '...' : '')
    })

    if (response.data.code === 200) {
      currentSessionId.value = response.data.data

      // 创建新会话后，重新获取会话列表以确保排序正确
      await fetchSessions()

      return response.data.data
    } else {
      throw new Error('创建会话失败: ' + response.data.msg)
    }
  } catch (error) {
    console.error('创建会话失败:', error)
    throw error
  }
}

// 发送消息
const handleSendMessage = async () => {
  if (!userInput.value.trim() || isLoading.value) return

  const userMessage = userInput.value.trim()
  userInput.value = ''

  // 添加用户消息
  chatMessages.push({
    role: 'user',
    content: userMessage,
    time: formatTime(),
    isStreaming: false
  })

  scrollToBottom()

  // 添加AI消息占位符
  const aiMessageIndex = chatMessages.push({
    role: 'ai',
    content: '',
    time: formatTime(),
    isStreaming: true
  }) - 1

  isLoading.value = true
  requestStatus.value = '准备请求...'

  try {
    // 检查用户ID
    if (!userStore.user_id) {
      throw new Error('用户ID为空，请重新登录')
    }

    let conversationId = currentSessionId.value

    // 如果是新会话，先创建会话
    if (!conversationId) {
      conversationId = await createSessionAndGetId(userMessage)
    }

    // 构建请求参数
    const params = {
      query: userMessage,
      conversationId: conversationId
    }

    console.log('发送请求参数:', params)

    requestStatus.value = '发送请求中...'

    // 使用fetch API处理流式响应
    const queryString = new URLSearchParams(params).toString()
    const url = `http://localhost:19000/chat/self/memory/chat?${queryString}`

    console.log('完整请求URL:', url)
    const myHeaders = new Headers();
    myHeaders.append('Content-Type', 'application/json');

    const response = await fetch(url, {
      method: 'GET',
      headers: myHeaders,
      credentials: 'include'
    })

    if (!response.ok) {
      throw new Error(`HTTP错误: ${response.status} ${response.statusText}`)
    }

    if (!response.body) {
      throw new Error('响应体为空')
    }

    requestStatus.value = '接收流式数据中...'

    // 处理流式响应
    const reader = response.body.getReader()
    const decoder = new TextDecoder('utf-8')
    let aiResponse = ''

    while (true) {
      const { done, value } = await reader.read()

      if (done) {
        // 流式响应结束
        chatMessages[aiMessageIndex].isStreaming = false
        requestStatus.value = '请求完成'

        // 更新会话列表
        await fetchSessions()
        break
      }

      // 解码并处理数据
      const chunk = decoder.decode(value, { stream: true })
      aiResponse += chunk

      // 更新AI消息内容
      chatMessages[aiMessageIndex].content = aiResponse
      scrollToBottom()
    }

  } catch (error) {
    console.error('请求AI接口失败:', error)

    // 移除AI消息占位符
    chatMessages.splice(aiMessageIndex, 1)

    // 添加错误消息
    let errorMessage = '抱歉，AI服务暂时不可用，请稍后重试。'

    if (error.message.includes('Failed to fetch')) {
      errorMessage = '无法连接到后端服务，请检查：1. 后端服务是否运行 2. 端口19000是否被占用 3. 是否存在跨域问题'
    } else if (error.message.includes('用户ID为空')) {
      errorMessage = '用户信息异常，请重新登录'
    } else if (error.message.includes('getReader')) {
      errorMessage = '浏览器不支持流式响应，请尝试使用现代浏览器如Chrome、Firefox或Edge'
    }

    chatMessages.push({
      role: 'ai',
      content: errorMessage,
      time: formatTime(),
      isStreaming: false
    })

    requestStatus.value = `请求失败: ${error.message}`
    ElMessage.error(`请求失败: ${error.message}`)
  } finally {
    isLoading.value = false
    scrollToBottom()
  }
}

// 初始化
onMounted(() => {
  // 添加欢迎消息
  chatMessages.push({
    role: 'ai',
    content: '您好！我是AI助手，很高兴为您服务。请问有什么可以帮助您的吗？',
    time: formatTime(),
    isStreaming: false
  })

  // 检查用户登录状态并获取会话列表
  if (userStore.user_id) {
    fetchSessions()
  } else {
    ElMessage.warning('检测到用户信息异常，建议重新登录')
  }
})

// 监听消息变化，自动滚动
watch(chatMessages, () => {
  scrollToBottom()
}, { deep: true })
</script>

<style scoped>
.home-container {
  height: 100vh;
  background: #f5f5f5;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0;
}

.chat-layout {
  display: flex;
  width: 100%;
  height: 100vh;
  max-width: 1200px;
  background: white;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

/* 左侧会话列表样式 */
.session-sidebar {
  width: 300px;
  border-right: 1px solid #e0e0e0;
  background: #fafafa;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #e0e0e0;
  background: white;
}

.sidebar-header h3 {
  margin: 0 0 15px 0;
  font-size: 18px;
  color: #333;
}

.session-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.session-item {
  padding: 15px;
  margin-bottom: 10px;
  background: white;
  border-radius: 8px;
  cursor: pointer;
  border: 1px solid #e0e0e0;
  transition: all 0.3s ease;
}

.session-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.session-item.active {
  border-color: #409eff;
  background: #f0f7ff;
}

.session-title {
  font-weight: 600;
  font-size: 14px;
  color: #333;
  margin-bottom: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.session-time {
  font-size: 12px;
  color: #999;
  margin-bottom: 8px;
}

.session-preview {
  font-size: 12px;
  color: #666;
  line-height: 1.4;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

/* 右侧聊天区域样式 */
.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.message {
  display: flex;
  gap: 12px;
  max-width: 100%;
}

.message.user {
  flex-direction: row-reverse;
}

.message-avatar {
  flex-shrink: 0;
}

.message-content {
  flex: 1;
  max-width: calc(100% - 44px);
}

.message-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.sender-name {
  font-weight: 600;
  font-size: 14px;
  color: #333;
}

.message-time {
  font-size: 12px;
  color: #999;
}

.message-text {
  padding: 12px 16px;
  border-radius: 8px;
  background: #f8f9fa;
  line-height: 1.5;
  word-wrap: break-word;
  white-space: pre-wrap;
}

.message.user .message-text {
  background: #e3f2fd;
  color: #1976d2;
}

.message.ai .message-text {
  background: #f5f5f5;
  color: #333;
}

.streaming-cursor {
  display: inline-block;
  width: 8px;
  height: 16px;
  background: #666;
  margin-left: 2px;
  animation: blink 1s infinite;
}

@keyframes blink {
  0%, 50% { opacity: 1; }
  51%, 100% { opacity: 0; }
}

.loading-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  color: #666;
  font-size: 14px;
}

.input-area {
  border-top: 1px solid #e0e0e0;
  padding: 20px;
  background: white;
}

.input-container {
  display: flex;
  gap: 12px;
  align-items: flex-end;
}

.input-container :deep(.el-textarea) {
  flex: 1;
}

.input-container :deep(.el-textarea__inner) {
  border-radius: 8px;
  resize: none;
}

.send-button {
  height: 74px;
  border-radius: 8px;
  min-width: 80px;
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar,
.session-list::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track,
.session-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb,
.session-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover,
.session-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-layout {
    flex-direction: column;
  }

  .session-sidebar {
    width: 100%;
    height: 200px;
    border-right: none;
    border-bottom: 1px solid #e0e0e0;
  }
}
</style>